package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.User;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ReportServicelmpl implements ReportService {

    //获取这个日期间的营业额统计
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额的统计
     * //日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03
     * private String dateList;
     * <p>
     * //营业额，以逗号分隔，例如：406.0,1520.0,75.0
     * private String turnoverList;
     */


    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //从当前时间到结束时间的放到这个list集合
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate localDate : dateList) {

            //查询date日期对应的营业额，状态为已完成的订单合计
            //select sum(amount) from orders order_time > beginTime and order_time < endTime and status = 5
            //获取这一天的最小时间和最大时间，又因为orders表是有小时分秒的，所以要转换一下
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Double turnover = orderMapper.sumByDate(beginTime, endTime);
            if (turnover == null)
                turnover = 0.0;
            turnoverList.add(turnover);

        }

        //StringUtils.join(dateList,",");
        //StringUtils.join(turnoverList,",")

        return TurnoverReportVO.builder().
                dateList(StringUtils.join(dateList, ",")).
                turnoverList(StringUtils.join(turnoverList, ",")).
                build();
    }


    /**
     * 统计指定时间内的用户数据
     */

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {


        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //总用户 和新增用户
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newlUserList = new ArrayList<>();
        for (LocalDate localDate : dateList) {

            //查询date日期对应的营业额，状态为已完成的订单合计
            //select count(id) from user order_time > beginTime and order_time < endTime
            //获取这一天的最小时间和最大时间，又因为orders表是有小时分秒的，所以要转换一下
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Integer total = userMapper.countByDatetotal(endTime);
            totalUserList.add(total);

            Integer newcount = userMapper.countByDatenew(beginTime, endTime);
            newlUserList.add(newcount);
        }


        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newlUserList, ","))
                .build();
    }

    /**
     * //日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03
     * private String dateList;
     * <p>
     * //每日订单数，以逗号分隔，例如：260,210,215
     * private String orderCountList;
     * <p>
     * //每日有效订单数，以逗号分隔，例如：20,21,10
     * private String validOrderCountList;
     * <p>
     * //订单总数
     * private Integer totalOrderCount;
     * <p>
     * //有效订单数
     * private Integer validOrderCount;
     * <p>
     * //订单完成率
     * private Double orderCompletionRate;
     */


    @Override
    public OrderReportVO getordersStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        Integer total, valid; //总的订单数和有效订单数
        total = valid = 0;
        Double orderCompletionRate = 0.0; //订单完成率

        //每日订单数和有效
        List<Integer> orderList = new ArrayList<>();

        List<Integer> usefulorderList = new ArrayList<>();


        for (LocalDate localDate : dateList) {

            //查询date日期对应的营业额，状态为已完成的订单合计
            //select count(id) from user order_time > beginTime and order_time < endTime
            //获取这一天的最小时间和最大时间，又因为orders表是有小时分秒的，所以要转换一下
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Integer tem = orderMapper.counttotalByDate(beginTime, endTime);
            orderList.add(tem);
            Integer tem1 = orderMapper.countUsefulByDate(beginTime, endTime);
            usefulorderList.add(tem1);

            total += tem;
            valid += tem1;
        }
        if (total != 0) {
            orderCompletionRate = (double) valid / total;
        }


        return OrderReportVO.builder().
                dateList(StringUtils.join(dateList, ",")).
                orderCountList(StringUtils.join(orderList, ",")).
                validOrderCountList(StringUtils.join(usefulorderList, ","))
                .totalOrderCount(total)
                .validOrderCount(valid)
                .orderCompletionRate(orderCompletionRate).
                build();
    }


    /**
     * 获得这个区间内销售前10统计
     *
     * @param begin
     * @param end
     * @return //商品名称列表，以逗号分隔，例如：鱼香肉丝,宫保鸡丁,水煮鱼
     * private String nameList;
     * <p>
     * //销量列表，以逗号分隔，例如：260,215,200
     * private String numberList;
     */

    @Override
    public SalesTop10ReportVO getSalesTop10Statistics(LocalDate begin, LocalDate end) {


        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        List<GoodsSalesDTO> goodsSalesDTOList = new ArrayList<>();


        //查询date日期对应的套餐或者菜品的数量和名字
        //select od.name, sum(od.number) from order_detail od , orders o where od.order_id = o.id and order_time > beginTime and order_time < endTime and o.status = 5
        //获取这一天的最小时间和最大时间，又因为orders表是有小时分秒的，所以要转换一下
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        goodsSalesDTOList = orderMapper.getSalesTop10(beginTime, endTime);

        for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOList) {

            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber());
        }


        return SalesTop10ReportVO.builder().
                nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ",")).
                build();
    }


    /**
     * 导出运营数据报表
     */

    @Override
    public void exportBusinessData(HttpServletResponse httpServletResponse) throws FileNotFoundException {

        //1.查询数据 获取营业数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2.通过pot将数据写入到Excel文件中
        InputStream in = new FileInputStream(new File("D:\\java\\cangqiongwaimai\\mode.xlsx"));
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获得第一个sheet
            XSSFSheet sheet = excel.getSheet("sheet1");

            //写入数据  日期
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            //获得第四行
            sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第五行
            XSSFRow row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充30天的明细数据
            for (int i = 0; i < 30; i++) {
                //查询莫一天的营业数据

                LocalDate date = dateBegin.plusDays(i);
                BusinessDataVO businessDataVO1 = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVO1.getTurnover());
                row.getCell(3).setCellValue(businessDataVO1.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO1.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO1.getNewUsers());

            }
            //3.通过response将文件写入到客户端
            ServletOutputStream out = httpServletResponse.getOutputStream();
            excel.write(out);


            out.close();
            excel.close();
            in.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
